<template>
  <BaseDialog
    v-model:visible="visible"
    title="保存为模板"
    icon="DocumentAdd"
    width="600px"
    :show-footer="false"
    :close-on-click-modal="false"
    @close="resetForm"
  >
    <div class="save-template-form">
      <!-- 模板信息表单 -->
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
        @submit.prevent="handleSubmit"
      >
        <el-form-item label="模板名称" prop="name">
          <BaseInput
            v-model="form.name"
            placeholder="请输入模板名称"
            prefix-icon="Document"
            size="large"
            maxlength="50"
            show-word-limit
            clearable
          />
        </el-form-item>

        <el-form-item label="模板描述" prop="description">
          <BaseInput
            v-model="form.description"
            type="textarea"
            placeholder="请描述这个模板的用途和特点..."
            :rows="4"
            maxlength="500"
            show-word-limit
          />
        </el-form-item>

        <el-form-item label="模板标签" prop="tags">
          <div class="tags-input">
            <el-tag
              v-for="tag in form.tags"
              :key="tag"
              closable
              @close="removeTag(tag)"
            >
              {{ tag }}
            </el-tag>
            <el-input
              v-if="inputVisible"
              ref="tagInput"
              v-model="inputValue"
              size="small"
              style="width: 100px"
              @keyup.enter="handleInputConfirm"
              @blur="handleInputConfirm"
            />
            <el-button
              v-else
              size="small"
              type="text"
              @click="showInput"
            >
              + 添加标签
            </el-button>
          </div>
          <div class="tags-tips">
            <el-text type="info" size="small">
              标签有助于其他用户找到您的模板
            </el-text>
          </div>
        </el-form-item>

        <el-form-item label="可见性设置">
          <el-radio-group v-model="form.isPublic" size="large">
            <el-radio :label="true">
              <div class="radio-option">
                <div class="radio-title">公开模板</div>
                <div class="radio-desc">所有用户都可以查看和使用</div>
              </div>
            </el-radio>
            <el-radio :label="false">
              <div class="radio-option">
                <div class="radio-title">私有模板</div>
                <div class="radio-desc">仅自己可以查看和使用</div>
              </div>
            </el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="模板分类" prop="category">
          <el-select
            v-model="form.category"
            placeholder="请选择模板分类"
            size="large"
            style="width: 100%"
          >
            <el-option
              v-for="category in templateCategories"
              :key="category.value"
              :label="category.label"
              :value="category.value"
            />
          </el-select>
        </el-form-item>
      </el-form>

      <!-- 包含的软件列表 -->
      <div class="software-list">
        <h4 class="section-title">包含的软件 ({{ selectedSoftware.length }})</h4>
        <div v-if="selectedSoftware.length > 0" class="software-grid">
          <div
            v-for="software in selectedSoftware"
            :key="software.id"
            class="software-item"
          >
            <div class="software-info">
              <div class="software-name">{{ software.displayName || software.name }}</div>
              <div class="software-version">v{{ software.version || 'latest' }}</div>
            </div>
            <el-tag :type="getCategoryType(software.category)" size="small">
              {{ software.category || '其他' }}
            </el-tag>
          </div>
        </div>
        <el-empty v-else description="暂无选择的软件" :image-size="80" />
      </div>

      <!-- 操作按钮 -->
      <div class="form-actions">
        <BaseButton
          variant="outline"
          size="large"
          @click="visible = false"
        >
          取消
        </BaseButton>
        <BaseButton
          type="primary"
          size="large"
          :loading="saving"
          :disabled="selectedSoftware.length === 0"
          @click="handleSubmit"
        >
          保存模板
        </BaseButton>
      </div>
    </div>
  </BaseDialog>
</template>

<script setup>
import { ref, reactive, computed, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import { useSoftwareStore } from '../../stores/software'
import { useUserStore } from '../../stores/user'
// import { Document, DocumentAdd } from '@element-plus/icons-vue'
import BaseDialog from '../common/BaseDialog.vue'
import BaseInput from '../common/BaseInput.vue'
import BaseButton from '../common/BaseButton.vue'
import axios from 'axios'
import { TEMPLATE_CATEGORIES, getCategoryType } from '../../constants/templateCategories'

const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  }
})

const emit = defineEmits(['update:modelValue', 'success'])

const softwareStore = useSoftwareStore()
const userStore = useUserStore()
const formRef = ref()
const tagInput = ref()
const saving = ref(false)
const inputVisible = ref(false)
const inputValue = ref('')

const visible = computed({
  get: () => props.modelValue,
  set: (value) => emit('update:modelValue', value)
})

const selectedSoftware = computed(() => softwareStore.selectedSoftware)

const form = reactive({
  name: '',
  description: '',
  tags: [],
  isPublic: true,
  category: ''
})

const templateCategories = TEMPLATE_CATEGORIES

const rules = {
  name: [
    { required: true, message: '请输入模板名称', trigger: 'blur' },
    { min: 2, max: 50, message: '模板名称长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  description: [
    { required: true, message: '请输入模板描述', trigger: 'blur' },
    { min: 10, max: 500, message: '模板描述长度在 10 到 500 个字符', trigger: 'blur' }
  ],
  category: [
    { required: true, message: '请选择模板分类', trigger: 'change' }
  ]
}



// 显示标签输入框
const showInput = () => {
  inputVisible.value = true
  nextTick(() => {
    tagInput.value?.focus()
  })
}

// 确认输入标签
const handleInputConfirm = () => {
  const value = inputValue.value.trim()
  if (value && !form.tags.includes(value) && form.tags.length < 5) {
    form.tags.push(value)
  }
  inputVisible.value = false
  inputValue.value = ''
}

// 移除标签
const removeTag = (tag) => {
  const index = form.tags.indexOf(tag)
  if (index > -1) {
    form.tags.splice(index, 1)
  }
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return

  if (selectedSoftware.value.length === 0) {
    ElMessage.warning('请先选择要包含在模板中的软件')
    return
  }

  try {
    await formRef.value.validate()
    saving.value = true

    const templateData = {
      name: form.name,
      description: form.description,
      tags: form.tags,
      isPublic: form.isPublic,
      category: form.category,
      softwareList: selectedSoftware.value.map(software => ({
        id: software.id,
        name: software.name,
        displayName: software.displayName,
        version: software.version,
        category: software.category,
        downloadUrl: software.downloadUrl,
        installCommand: software.installCommand,
        configOptions: software.configOptions
      }))
    }

    const response = await axios.post('/templates', templateData, {
      headers: {
        'Authorization': `Bearer ${userStore.token}`
      }
    })

    if (response.data.success) {
      ElMessage.success('模板保存成功！')
      visible.value = false
      emit('success', response.data.data)
      resetForm()
    } else {
      throw new Error(response.data.message || '保存模板失败')
    }
  } catch (error) {
    console.error('保存模板失败:', error)
    ElMessage.error('保存模板失败: ' + error.message)
  } finally {
    saving.value = false
  }
}

// 重置表单
const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields()
  }
  Object.assign(form, {
    name: '',
    description: '',
    tags: [],
    isPublic: true,
    category: ''
  })
  inputVisible.value = false
  inputValue.value = ''
}
</script>

<style scoped>
.save-template-form {
  padding: 0;
  max-height: 100%;
  overflow: visible;
}

.tags-input {
  display: flex;
  flex-wrap: wrap;
  gap: var(--spacing-sm);
  align-items: center;
  min-height: 32px;
}

.tags-tips {
  margin-top: var(--spacing-xs);
}

.radio-option {
  margin-left: var(--spacing-sm);
}

.radio-title {
  font-weight: var(--font-weight-medium);
  color: var(--color-text-primary);
  margin-bottom: 2px;
}

.radio-desc {
  font-size: var(--font-size-sm);
  color: var(--color-text-secondary);
}

.software-list {
  margin: var(--spacing-lg) 0;
  padding: var(--spacing-lg);
  background: var(--color-bg-secondary);
  border-radius: var(--radius-lg);
  border: 1px solid var(--color-border-light);
}

.section-title {
  margin: 0 0 var(--spacing-lg) 0;
  font-size: var(--font-size-lg);
  font-weight: var(--font-weight-semibold);
  color: var(--color-text-primary);
}

.software-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
  gap: var(--spacing-md);
}

.software-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: var(--spacing-md);
  background: var(--color-bg-primary);
  border: 1px solid var(--color-border-light);
  border-radius: var(--radius-md);
  transition: var(--transition-fast);
}

.software-item:hover {
  border-color: var(--color-primary);
  box-shadow: var(--shadow-sm);
}

.software-info {
  flex: 1;
  min-width: 0;
}

.software-name {
  font-weight: var(--font-weight-medium);
  color: var(--color-text-primary);
  margin-bottom: 2px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.software-version {
  font-size: var(--font-size-sm);
  color: var(--color-text-secondary);
}

.form-actions {
  display: flex;
  justify-content: flex-end;
  gap: var(--spacing-md);
  margin-top: var(--spacing-lg);
  padding-top: var(--spacing-lg);
  border-top: 1px solid var(--color-border-light);
}

/* 表单样式优化 */
:deep(.el-form-item__label) {
  font-weight: var(--font-weight-medium);
  color: var(--color-text-primary);
  margin-bottom: var(--spacing-sm);
}

:deep(.el-radio-group) {
  display: flex;
  flex-direction: column;
  gap: var(--spacing-md);
}

:deep(.el-radio) {
  margin-right: 0;
  margin-bottom: 0;
  align-items: flex-start;
}

:deep(.el-radio__input) {
  margin-top: 2px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .software-grid {
    grid-template-columns: 1fr;
  }
  
  .form-actions {
    flex-direction: column-reverse;
    gap: var(--spacing-sm);
  }
  
  .form-actions .base-button {
    width: 100%;
  }
}

@media (max-width: 480px) {
  .software-item {
    flex-direction: column;
    align-items: flex-start;
    gap: var(--spacing-sm);
  }
  
  .tags-input {
    flex-direction: column;
    align-items: flex-start;
  }
}
</style>
